/* This file is part of HealthyFood.

   HealthyFood is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   HealthyFood is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
    
   You should have received a copy of the GNU General Public License
   along with HealthyFood.  If not, see <http://www.gnu.org/licenses/>.

	Portions of this file are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

*	copyright (c) 2009 Vytautas Kasparavičius
*/ 

package com.healthyFood;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbAdapter {
	public static final String KEY_BARCODE = "_barcode";
	public static final String KEY_TITLE = "title";
	public static final String KEY_CONTENTS = "contents";

	private static final String TAG = "DbAdapter";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	/**
	 * Database creation sql statement
	 */
	private static final String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS Food (_barcode big primary key, title text not null, contents text not null);";

	private static final String DATABASE_NAME = "data";
	private static final String DATABASE_TABLE = "Food";
	private static final int DATABASE_VERSION = 1;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
			db.execSQL("INSERT INTO Food (_barcode, title, contents) VALUES (4750449000401, 'Smoked Squid Strip', 'squid,salt,sodium glutamate (621)');");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS notes");
			onCreate(db);
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public DbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public DbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Create a new database item (product). If the product is
	 * successfully created return the new rowId for that product, otherwise return
	 * a -1 to indicate failure.
	 * 
	 * @param barcode
	 *            barcode of product
	 * @param title
	 *            product title
	 * @param contents
	 * 			  contents of product
	 * @return barcode or -1 if failed
	 */
	public long addProduct(Long barcode, String title, String contents) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_BARCODE, barcode);
		initialValues.put(KEY_TITLE, title);
		initialValues.put(KEY_CONTENTS, contents);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Delete the product with the given barcode
	 * 
	 * @param rowId
	 *            id of note to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deleteProduct(Long barcode) {
		return mDb.delete(DATABASE_TABLE, KEY_BARCODE + "=" + barcode, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all products in the database
	 * 
	 * @return Cursor over all products
	 */
	public Cursor fetchAllProducts() {
		return mDb.query(DATABASE_TABLE, new String[] { KEY_BARCODE, KEY_TITLE,
				KEY_CONTENTS }, null, null, null, null, null);
	}

	/**
	 * Return a Cursor positioned at the product that matches the given barcode
	 * 
	 * @param barcode
	 *            barcode of product to retrieve
	 * @return Cursor positioned to matching product, if found
	 * @throws SQLException
	 *             if note could not be found/retrieved
	 */
	public Cursor fetchProduct(long barcode) throws SQLException {

		Cursor mCursor =

		mDb.query(true, DATABASE_TABLE, new String[] { KEY_BARCODE, KEY_TITLE,
				KEY_CONTENTS }, KEY_BARCODE + "=" + barcode, null, null, null, null,
				null);
		
		if (mCursor != null) {
			if (mCursor.getCount() > 0) {
				mCursor.moveToFirst();
			}
		}
		return mCursor;
	}

	/**
	 * Update the product using the details provided. The product to be updated is
	 * specified using the barcode, and it is altered to use the title and contents
	 * values passed in
	 * 
	 * @param barcode
	 *            barcode of product to update
	 * @param title
	 *            value to set product title to
	 * @param contents
	 *            value to set product contents to
	 * @return true if the note was successfully updated, false otherwise
	 */
	public boolean updateProduct(long barcode, String title, String contents) {
		ContentValues args = new ContentValues();
		args.put(KEY_TITLE, title);
		args.put(KEY_CONTENTS, contents);

		return mDb.update(DATABASE_TABLE, args, KEY_BARCODE + "=" + barcode, null) > 0;
	}
}
